package com.awakening.server;

import com.awakening.message.Const;
import com.awakening.message.Message;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.util.UUID;

/**
 * Netty主要handler
 * @Author:AwakeningCode
 * @Date: Created in 19:46 2018\2\4 0004
 */
public class ServerHandler extends ChannelInboundHandlerAdapter{

    private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);

    static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            Message message = (Message)msg;
            String dataString = new String(message.getData(), CharsetUtil.UTF_8);
            log.info(String.format("Receive message: %s",dataString));
            ctx.writeAndFlush(Unpooled.copiedBuffer(ByteBuffer.allocateDirect(Const.StateEnum.SUCCESS.getStateInfo())));
        }finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Const.add(String.valueOf(Const.getSzie()+1),ctx.channel());
        channels.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("Disconnected client " + ctx.channel().remoteAddress());
        Const.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        log.warn(cause.getMessage());
    }
}
